<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>角色管理</title>
		<link href="/component/pear/css/pear.css" rel="stylesheet" />
	</head>
	<body class="pear-container">
		<div class="layui-card">
			<div class="layui-card-body">
				<form class="layui-form" action="">
					<div class="layui-form-item">
						<div class="layui-form-item layui-inline">
							<label class="layui-form-label">角色名</label>
							<div class="layui-input-inline">
								<input type="text" name="roleName" placeholder="" class="layui-input">
							</div>
						</div>
						<div class="layui-form-item layui-inline">
							<label class="layui-form-label">角色标识</label>
							<div class="layui-input-inline">
								<input type="text" name="roleCode" placeholder="" class="layui-input">
							</div>
						</div>
						<div class="layui-form-item layui-inline">
							<button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="role-query">
								<i class="layui-icon layui-icon-search"></i>
								查询
							</button>
							<button type="reset" class="pear-btn pear-btn-md">
								<i class="layui-icon layui-icon-refresh"></i>
								重置
							</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		<div class="layui-card">
			<div class="layui-card-body">
				<table id="role-table" lay-filter="role-table"></table>
			</div>
		</div>

		<input type="text" id="rolePermIds"  style="display: none">

		<script type="text/html" id="role-toolbar">
			<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
				<i class="layui-icon layui-icon-add-1"></i>
				新增
			</button>
			<button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove">
				<i class="layui-icon layui-icon-delete"></i>
				删除
			</button>
		</script>

		<script type="text/html" id="role-bar">
			<button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i></button>
			<button class="pear-btn pear-btn-warming pear-btn-sm" lay-event="power"><i class="layui-icon layui-icon-vercode"></i></button>
			<button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i class="layui-icon layui-icon-delete"></i></button>
		</script>

		<%--<script type="text/html" id="role-enable">
			<input type="checkbox" name="enable" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="user-enable" checked = "{{ d.id == 10003 ? 'true' : 'false' }}">
		</script>--%>

		<script type="text/html" id="role-enable">
			{{#if (d.enable == 1) { }}
			<input type="checkbox" name="enable" value="{{d.roleId}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="role-enable" checked>
			{{# }else if(d.enable == 0){ }}
			<input type="checkbox" name="enable" value="{{d.roleId}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="role-enable" >
			{{# } }}
		</script>


		<script src="/component/layui/layui.js"></script>
		<script src="/component/pear/pear.js"></script>
		<script>
		    layui.use(['table','form','jquery','common','dtree'],function () {
		        let table = layui.table;
		        let form = layui.form;
		        let $ = layui.jquery;
				let common = layui.common;
				let dtree = layui.dtree;

		        let cols = [
		            [
		                {type:'checkbox'},
		                {title: '角色名', field: 'roleName', align:'center', width:100},
		                {title: '角色标识', field: 'roleCode', align:'center'},
		                {title: '角色描述', field: 'details', align:'center'},
						{
							title: '注册时间',
							field: 'createTime',
							align: 'center'
						},
		                {title: '是否可用', field: 'enable', align:'center', templet:'#role-enable'},
		                {title: '操作', toolbar: '#role-bar', align:'center', width:195}
		            ]
		        ]

		        table.render({
		            elem: '#role-table',
		            url: '/role/list',
		            page: true ,
		            cols: cols ,
		            skin: 'line',
		            toolbar: '#role-toolbar',
		            defaultToolbar: [{
						title: '刷新',
		                layEvent: 'refresh',
		                icon: 'layui-icon-refresh',
		            }, 'filter', 'print', 'exports']
		        });

		        table.on('tool(role-table)', function(obj){
		            if(obj.event === 'remove'){
		                window.remove(obj);
		            } else if(obj.event === 'edit'){
		                window.edit(obj);
		            } else if(obj.event === 'power'){
		                window.power(obj);
		            }
		        });

		        table.on('toolbar(role-table)', function(obj){
		            if(obj.event === 'add'){
		                window.add();
		            } else if(obj.event === 'refresh'){
		                window.refresh();
		            } else if(obj.event === 'batchRemove'){
		                window.batchRemove(obj);
		            }
		        });

		        form.on('submit(role-query)', function(data){
		            table.reload('role-table',{where:data.field})
		            return false;
		        });


				form.on('switch(role-enable)', function(data) {
					var enable = data.elem.checked?'1':'0';
					$.ajax({
						url: "/role/enable/" + data.value + "/" + enable,
						dataType: 'json',
						type: 'POST',
						success: function(result) {
							window.refresh();
						},
						error: function (data) {
							layer.msg(data.responseJSON.detail,{icon:2,time:1000});
						}
					});
				})

		        window.add = function(){
		            layer.open({
		                type: 2,
		                title: '新增',
		                shade: 0.1,
		                area: ['500px', '300px'],
		                content: '/role-add'
		            });
		        }

				/**
				 * 授权，使用dtree组件渲染
				 * @param obj
				 */
				window.power = function(obj){
					layer.open({
						type: 1, //type:0 也行
						title: "角色授权",
						area: ["400px", "80%"],
						content: '<ul id="openTree5" class="dtree" data-id="0"></ul>',
						btn: ['确认授权'],
						success: function(layero, index){
							//用于角色对应权限回显 start
							$.ajax({
								url: "/get-role-perms",
								type: 'GET',
								data: {'roleId':obj.data.roleId},
								success: function(result) {
									let roles = result.data.map(item=>{
										return item.powerId;
									});
									$("#rolePermIds").val(roles.join(","));
								}
							});
							//用于角色对应权限回显 end

							var DTree = dtree.render({
								obj: $(layero).find("#openTree5"),
								dataStyle: "layuiStyle",
								response:{message:"msg",statusCode:0},
								icon: ["0","-1"],
								url: "/perm-all",
								checkbar: true, // 开启复选框
								done: function(data, obj, first){  //使用异步加载回调
									if(first) {
										var rolePermIds = $("#rolePermIds").val();
										dtree.chooseDataInit("openTree5", rolePermIds); // 初始化复选框的值
									}
								}
							});
						},
						yes: function(index, layero) {
							var flag = true;
							var params = dtree.getCheckbarNodesParam("openTree5"); // 获取选中值
							if(params.length == 0){
								layer.msg("请至少选择一个节点",{icon:2});
								flag = false;
							}
							// 设置复选框的值，也可以用示例3的方式
							var ids = [], names = [];
							for(var key in params){
								var param = params[key];
								ids.push(param.nodeId);
								names.push(param.context);
							}
							$("#rolePermIds").val(ids.join(","));
							//传入后台修改角色对应权限
							if (flag){
								$.ajax({
									url: "/create/role-perm",
									contentType: 'application/json',
									data: JSON.stringify({'roleId':obj.data.roleId,'permIds': ids}),
									type: 'POST',
									success: function(result) {
										layer.msg('操作成功', {
											icon: 1,
											time: 1000
										}, function() {
											layer.close(index);
										});
									},
									error: function (data) {
										layer.msg(data.responseJSON.detail,{icon:2,time:1000});
										flag = false;
									}
								});
							}
						}
					});
				}

		        window.edit = function(obj){
		            layer.open({
		                type: 2,
		                title: '修改',
		                shade: 0.1,
		                area: ['500px', '300px'],
		                content: '/role-edit',
						success:function (layero,index) {
							var iframe = window['layui-layer-iframe' + index];
							//将表格列内容传递给弹框，用户数据回显
							iframe.init(obj.data)
						}
		            });
		        }

		        window.remove = function(obj){
		            layer.confirm('确定要删除该角色', {icon: 3, title:'提示'}, function(index){
		                layer.close(index);
		                let loading = layer.load();
		                $.ajax({
		                    url: "role/delete/"+obj.data['roleId'],
		                    dataType:'json',
		                    type:'post',
		                    success:function(result){
		                        layer.close(loading);
		                        if(result.success){
		                            layer.msg(result.msg,{icon:1,time:1000},function(){
										table.reload('role-table');
		                            });
		                        }
		                    },
							error: function (data) {
								layer.close(loading);
								layer.msg(data.responseJSON.detail,{icon:2,time:1000});
							}
		                })
		            });
		        }

				window.batchRemove = function(obj) {
					var checkIds = common.checkField(obj,'roleId');
					if (checkIds === "") {
						layer.msg("未选中数据", {
							icon: 3,
							time: 1000
						});
						return false;
					}
					layer.confirm('确定要删除这些角色', {
						icon: 3,
						title: '提示'
					}, function(index) {
						layer.close(index);
						let loading = layer.load();
						$.ajax({
							url: "/role/batch-remove/" + checkIds,
							dataType: 'json',
							type: 'delete',
							success: function(result) {
								layer.close(loading);
								if (result.success) {
									layer.msg('操作成功', {
										icon: 1,
										time: 1000
									}, function() {
										table.reload('role-table');
									});
								}
							},
							error: function (data) {
								layer.close(loading);
								layer.msg(data.responseJSON.detail,{icon:2,time:1000});
							}
						})
					});
				}

		        window.refresh = function(){
		            table.reload('role-table');
		        }
		    })
		</script>
	</body>
</html>
